package org.jeecgframework.web.system.controller.core;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.ComboTree;
import org.jeecgframework.core.common.model.json.TreeGrid;
import org.jeecgframework.core.common.model.json.ValidForm;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MutiLangUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.tag.vo.easyui.ComboTreeModel;
import org.jeecgframework.tag.vo.easyui.TreeGridModel;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.system.pojo.base.TSTerritory;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


/**
 * 地域处理类
 * @author wushu
 */
@Scope("prototype")
@Controller
@RequestMapping("/territoryController")
public class TerritoryController extends BaseController {
	
	private String message = null;

    @Autowired
    private ZyCommonService zyCommonService;

	@Autowired
	private SystemService systemService;

	/**
	 * 地域列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "territory")
	public ModelAndView function() {
		return new ModelAndView("system/territory/territoryList");
	}

	
	/**
	 * 地域列表
	 */
	@RequestMapping(params = "territoryGrid")
	@ResponseBody
	public List<TreeGrid> territoryGrid(HttpServletRequest request, TreeGrid treegrid) {
		CriteriaQuery cq = new CriteriaQuery(TSTerritory.class);
			if (treegrid.getId() != null) {
				cq.eq("TSTerritory.id", treegrid.getId());
			}
			if (treegrid.getId() == null) {
				cq.isNull("TSTerritory.id");//这个是全国最高级
			}
		
		cq.addOrder("territorySort", SortDirection.asc);
		cq.add();
		List<TSTerritory> territoryList = systemService.getListByCriteriaQuery(cq, false);
		List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
		TreeGridModel treeGridModel = new TreeGridModel();
		treeGridModel.setIcon("");
		treeGridModel.setTextField("territoryName");
		treeGridModel.setParentText("TSTerritory_territoryName");
		treeGridModel.setParentId("TSTerritory_id");
		treeGridModel.setSrc("territoryCode");
		treeGridModel.setIdField("id");
		treeGridModel.setChildList("TSTerritorys");
		treeGridModel.setOrder("territorySort");
		treeGrids = systemService.treegrid(territoryList, treeGridModel);
		return treeGrids;
	}
	
	/**
	 * 地域 添加跳转
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(TSTerritory territory, HttpServletRequest req) {
		if(territory.getTSTerritory() != null && territory.getTSTerritory().getId() != null){
			territory.setTSTerritory((TSTerritory)systemService.getEntity(TSTerritory.class, territory.getTSTerritory().getId()));
			req.setAttribute("territory", territory);
		}
		return new ModelAndView("system/territory/territory-add");
	}
	
	/**
	 * @author xiul
	 * 2016-6-14 下午5:12:16
	 * Description 选择地域 页面跳转 - 地域编辑页用
	 */
	@RequestMapping(params="goChooseTerritory")
	public ModelAndView goChooseTerritory(){
		return new ModelAndView("system/territory/chooseTerrytory");
	}
	
	/**
	 * @author xiul
	 * 2016-6-14 下午5:13:14
	 * Description 选择地域树形datagird  - 地域编辑页用
	 */
	@ResponseBody
	@RequestMapping(params="chooseTerritoryList")
	public List<TreeGrid> chooseTerritoryList(TSTerritory tsTerritory,HttpServletRequest request,HttpServletResponse response,TreeGrid treegrid){
		CriteriaQuery cq;
		List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
		cq = new CriteriaQuery(TSTerritory.class);
		if (treegrid.getId() != null) {
			cq.eq("TSTerritory.id", treegrid.getId());
		}else if(treegrid.getId() == null){
			cq.isNull("TSTerritory.id");
		}
		cq.add();
        List<TSTerritory> tsTerritoryList = systemService.getListByCriteriaQuery(cq, false);
        TreeGridModel treeGridModel = new TreeGridModel();
        treeGridModel.setIdField("id");
		treeGridModel.setTextField("territoryName");
		treeGridModel.setParentId("TSTerritory_id");
		treeGridModel.setParentText("TSTerritory_territoryName");
		treeGridModel.setSrc("");
		treeGridModel.setChildList("TSTerritorys");
		treeGrids = systemService.treegrid(tsTerritoryList, treeGridModel);
		return treeGrids;
	}
	
	/**
	 * 地域 编辑跳转
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(TSTerritory territory, HttpServletRequest req) {
		String id = req.getParameter("id");
		if (StringUtil.isNotEmpty(id)) {
			territory = systemService.getEntity(TSTerritory.class, id);
		}
		if(territory.getTSTerritory() != null && territory.getTSTerritory().getId() != null){
			territory.setTSTerritory((TSTerritory)systemService.getEntity(TSTerritory.class, territory.getTSTerritory().getId()));
		}
		req.setAttribute("territory", territory);
		return new ModelAndView("system/territory/territory-update");
	}
	
	
	/**
	 * 地域父级下拉菜单
	 */
	@RequestMapping(params = "setPTerritory")
	@ResponseBody
	public List<ComboTree> setPTerritory(HttpServletRequest request, ComboTree comboTree) {
		CriteriaQuery cq = new CriteriaQuery(TSTerritory.class);
		if (comboTree.getId() != null) {
			cq.eq("TSTerritory.id", comboTree.getId());
		}
		if (comboTree.getId() == null) {
			cq.isNull("TSTerritory");
		}
		cq.add();
		List<TSTerritory> territoryList = systemService.getListByCriteriaQuery(cq, false);
		List<ComboTree> comboTrees = new ArrayList<ComboTree>();
		ComboTreeModel comboTreeModel = new ComboTreeModel("id", "territoryName", "TSTerritorys");
		comboTrees = systemService.comboTree(territoryList, comboTreeModel, null, false);
		return comboTrees;
	}
	
	/**
	 * @author xiul
	 * 2016-6-28 下午8:09:00
	 * Description 检查地域名称的唯一性 
	 * @param param 地域名称
	 * @param id 主键
	 */
	@ResponseBody
	@RequestMapping(params="checkAreaNameUnique")
	public ValidForm checkAreaNameUnique(@RequestParam(value="param",defaultValue="")String param,
			@RequestParam(value="id",defaultValue="")String id,
			@RequestParam(value="level",defaultValue="")String level
			){
		ValidForm vf = new ValidForm();
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT COUNT(1) AS total ");
		sql.append(" FROM t_s_territory tt");
		sql.append(" WHERE ");
		sql.append(" tt.territoryName = '"+param+"' ");
		if(StringUtil.isNotEmpty(id)){
			sql.append(" AND tt.id != '"+id+"' ");
		}
		//查询同等级 的地域名 不包括自己的 是否有重名的
		if(StringUtil.isNotEmpty(level)){
			sql.append(" AND tt.territorylevel = '"+level+"' ");
		}
		int total = zyCommonService.getCountBySql(sql.toString());
		if(total > 0){
			vf.setStatus(ValidForm.N);
			vf.setInfo("当前地域名称已经存在");
		}
		return vf;
	}
	
	/**
	 * 地域保存
	 */
	@RequestMapping(params = "saveTerritory")
	@ResponseBody
	public AjaxJson saveTerritory(TSTerritory territory, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		if (territory.getTSTerritory().getId().equals("")) {
			territory.setTerritoryLevel((short)1);
			territory.setTSTerritory(null);
		}else{
			territory.setTerritoryLevel((short)2);
			TSTerritory parent = systemService.getEntity(TSTerritory.class, territory.getTSTerritory().getId());
			List<Map<String, Object>> forJdbc = systemService.findForJdbc("select * from t_s_territory where territoryparentid='" + parent.getId() + "' ORDER BY territorysort desc");
			boolean flag = true;
			if(forJdbc.size() != 0){
				for(int i = 0;i<forJdbc.size();i++){
					if(forJdbc.get(i).get("territoryName").equals(territory.getTerritoryName())){
						flag = false;
						break;
					}
				}
			}

				if (StringUtil.isNotEmpty(parent.getTerritoryCode())) {
					if (forJdbc.size() != 0) {
						int territorycode = Integer.parseInt(forJdbc.get(0).get("territorycode").toString());
						if(flag) {
							territorycode += 1;
						}else{
							List<Map<String, Object>> forJdbc1 = systemService.findForJdbc("select territorycode from t_s_territory where id = '" + territory.getId() + "'");
							territorycode = Integer.parseInt(forJdbc1.get(0).get("territorycode").toString());
						}
						territory.setTerritoryCode(Integer.toString(territorycode));
					} else {
						String territoryCode = parent.getTerritoryCode();
						territoryCode += "100";
						territory.setTerritoryCode(territoryCode);
					}
				}
				territory.setTerritoryLevel(Short.valueOf(parent.getTerritoryLevel() + 1 + ""));

		 }
		if (StringUtil.isNotEmpty(territory.getId())) {
			message = "地域: " + territory.getTerritoryName() + "被更新成功";
			systemService.saveOrUpdate(territory);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);

            message = MutiLangUtil.paramUpdSuccess("common.area");
		} else {
			territory.setTerritorySort(territory.getTerritorySort());
			message = "地域: " + territory.getTerritoryName() + "被添加成功";
			systemService.save(territory);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);

            message = MutiLangUtil.paramAddSuccess("common.area");
        }

        j.setMsg(message);
		
		return j;
	}

	/**
	 * 地域删除
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(TSTerritory territory, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		territory = systemService.getEntity(TSTerritory.class, territory.getId());
		message = "地域: " + territory.getTerritoryName() + "被删除成功";
		systemService.delete(territory);
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);

        message = MutiLangUtil.paramDelSuccess("common.area");
        j.setMsg(message);
		return j;
	}

	/**
	 * @author xiul
	 * 2016-6-14 下午5:57:40
	 * Description 选择地域跳转 - 设备页用
	 */
	@RequestMapping(params = "goChooseTerritoryForEs")
    public ModelAndView goChooseTerritoryForEs(HttpServletRequest request) {
        return new ModelAndView("system/territory/chooseTerrytoryForEs");
    }
	
	/**
	 * @author xiul
	 * 2016-6-14 下午5:13:14
	 * Description 选择地域跳转 - 设备页用
	 */
	@ResponseBody
	@RequestMapping(params="chooseTerritoryForEsList")
	public List<TreeGrid> chooseTerritoryForEsList(TSTerritory tsTerritory,HttpServletRequest request,HttpServletResponse response,TreeGrid treegrid){
		CriteriaQuery cq;
		List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
		cq = new CriteriaQuery(TSTerritory.class);
		if (treegrid.getId() != null) {
			cq.eq("TSTerritory.id", treegrid.getId());
		}else if(treegrid.getId() == null){
			cq.isNull("TSTerritory.id");
		}
		cq.add();
        List<TSTerritory> tsTerritoryList = systemService.getListByCriteriaQuery(cq, false);
        TreeGridModel treeGridModel = new TreeGridModel();
        treeGridModel.setIdField("id");
		treeGridModel.setTextField("territoryName");
		treeGridModel.setParentId("TSTerritory_id");
		treeGridModel.setParentText("TSTerritory_territoryName");
		treeGridModel.setSrc("");
		treeGridModel.setChildList("TSTerritorys");
		treeGrids = systemService.treegrid(tsTerritoryList, treeGridModel);
		return treeGrids;
	}
	
	/**
	 * @author xiul
	 * 2016-6-14 下午5:57:40
	 * Description 选择地域跳转 - 影院页用
	 */
	@RequestMapping(params = "goChooseTerritoryForCm")
	public ModelAndView goChooseTerritoryForCm(HttpServletRequest request) {
		return new ModelAndView("system/territory/chooseTerrytoryForCm");
	}
	
	/**
	 * @author xiul
	 * 2016-6-14 下午5:13:14
	 * Description 选择地域跳转 - 影院页用
	 */
	@ResponseBody
	@RequestMapping(params="chooseTerritoryForCmList")
	public List<TreeGrid> chooseTerritoryForCmList(TSTerritory tsTerritory,HttpServletRequest request,HttpServletResponse response,TreeGrid treegrid){
		CriteriaQuery cq;
		List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
		cq = new CriteriaQuery(TSTerritory.class);
		if (treegrid.getId() != null) {
			cq.eq("TSTerritory.id", treegrid.getId());
		}else if(treegrid.getId() == null){
			cq.isNull("TSTerritory.id");
		}
		cq.add();
		List<TSTerritory> tsTerritoryList = systemService.getListByCriteriaQuery(cq, false);
		TreeGridModel treeGridModel = new TreeGridModel();
		treeGridModel.setIdField("id");
		treeGridModel.setTextField("territoryName");
		treeGridModel.setParentId("TSTerritory_id");
		treeGridModel.setParentText("TSTerritory_territoryName");
		treeGridModel.setSrc("");
		treeGridModel.setChildList("TSTerritorys");
		treeGrids = systemService.treegrid(tsTerritoryList, treeGridModel);
		return treeGrids;
	}
	
}
